﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace Kokomo
{
	class DragHelper
	{
		internal DragHelper(FrameworkElement element)
		{
			element.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(Element_MouseLeftButtonDown);
			element.MouseMove += new System.Windows.Input.MouseEventHandler(Element_MouseMove);
		}

		private FrameworkElement _element;
		private Point _mouseDownPoint;

		internal void Element_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			this._mouseDownPoint = e.GetPosition(this._element);
		}
		internal void Element_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
		{
			if (e.LeftButton == MouseButtonState.Pressed)
			{
				FrameworkElement element = (FrameworkElement)sender;

				Point startPoint = this._mouseDownPoint;
				Point newPoint = e.GetPosition(this._element);

				double dx = Math.Abs(startPoint.X - newPoint.X);
				double dy = Math.Abs(startPoint.Y - newPoint.Y);
				if (
					(dx >= 2)
					|| (dy >= 2)
					)
				{
					this.StartDrag(element);
				}
			}
		}

		protected void StartDrag(FrameworkElement element)
		{
			DragBehavior dragBehavior = DragDropHelper.GetDragBehavior(element);
			if (dragBehavior == null) return;

			DragDropEffects allowedEffects;
			IDataObject dataObject = dragBehavior.GetDataObject(element, out allowedEffects);
			DragDropEffects effect = DragDrop.DoDragDrop(element, dataObject, allowedEffects);

			dragBehavior.CompleteDrag(element, dataObject, effect);
		}
	}
}
